import {
  Controller,
  Get,
  Post,
  Put,
  Middleware
} from 'bitorjs';
const puppeteer = require('puppeteer');
const uuid = require('uuid');

function sleep(delay) {
  return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(1)
      }, delay)
  })
}

@Controller('/feps/performance')
export default class {

  @Get('/list')
  async list(ctx,next){
    const entry = await ctx.$service.performance.list(ctx.request.query);
    if(entry){
      const config = ctx.app.$config;
      ctx.success(entry.rows.map(item=>{
        console.log(item.getDataValue("timing"))
        return {
          title:item.getDataValue("title"),
          url:item.getDataValue("url"),
          shot: item.getDataValue("shot").replace(config.staticDir, `http://localhost:${config.port}`),
          timing: item.getDataValue("timing"),
          trace: item.getDataValue("traceurl").replace(config.staticDir, `http://localhost:${config.port}`),
          at: item.getDataValue('at')
        }
      }),{
        totalRecordSize: entry.count
      })
    } else {
      ctx.fail()
    }
  }
 
  @Post("/analize")
  async performanceAnalize(ctx, next){
    const params = ctx.request.body;
    
    console.log('请求进来')
    const browser = await puppeteer.launch({headless: true});
    console.log('成功启动分析器')
    const page = await browser.newPage();
    console.log('成功打开标签')

    // await page.pdf({path: 'hn.pdf', format: 'A4'});
    // 等待页面 加载完成
    // await page.waitForNavigation({
    //   waitUntil: "load",
    //   // timeout: 10000
    // })
    const config = ctx.app.$config;
    const filename = uuid.v1();
    const traceFilepath = `${config.staticDir}/${filename}.json`;
    await page.tracing.start({path: traceFilepath});
    
    await page.goto(params.url, {
      waitUntil: 'networkidle0'
    });
    console.log('打开网址')
    await page.tracing.stop();


    // // 滚动高度
    // let scrollStep = 1080;
    // // 最大滚动高度
    // let max_height = 30000;
    // let m = {prevScroll: -1, curScroll: 0}

    // while (m.prevScroll !== m.curScroll && m.curScroll < max_height) {
    //   m = await page.evaluate((scrollStep) => {
    //     if (document.scrollingElement) {
    //       let prevScroll = document.scrollingElement.scrollTop;
    //       document.scrollingElement.scrollTop = prevScroll + scrollStep; 
    //       let curScroll = document.scrollingElement.scrollTop
    //       return {prevScroll, curScroll}
    //     }
    //   }, scrollStep);

    //   await sleep(1000);
    // }

    
    
    const filepath = `${config.staticDir}/${filename}.png`;
    await page.screenshot({path: filepath, fullPage: false});
    console.log('截图成功')
    const timingStr = await page.evaluate(()=>{

      return  JSON.stringify(window.performance.timing)
    })

    const title = await page.evaluate(()=>{
      return window.document.title;
    })

    await page.close();
    await browser.close();
    console.log('关闭分析器')
    // 数据录入
    const entry = ctx.$service.performance.add({
      shot: filepath,
      title: title,
      url: params.url,
      timing: timingStr,
      traceurl: traceFilepath,
    })

    // 录入结果
    ctx.success({
      shot: filepath.replace(config.staticDir, `http://localhost:${config.port}`),
      timing: timingStr,
      trace: traceFilepath.replace(config.staticDir, `http://localhost:${config.port}`),
      url: params.url,
      title: title
    })
    
    // 分析
    // ctx.success({
    //   shot: filepath.replace(config.staticDir, `http://localhost:${config.port}`),
    //   timing: JSON.parse(timingStr)
    // })
  }
}